// https://leetcode.cn/problems/subarrays-with-k-different-integers/description/

class Solution {
public:
    int subarraysWithKDistinct(vector<int>& nums, int k) {
        auto solve = [&](vector<int>& a, int k) -> int {
            int n = a.size();
            int sum = 0, j = 0, now = 0;
            map<int, int> cnt;
            for (int i = 0; i < n; i++) {
                cnt[a[i]]++;
                if (cnt[a[i]] == 1) now++;
                while (now > k) {
                    cnt[a[j]]--;
                    if (!cnt[a[j]]) now--;
                    j++;
                }
                sum += i - j;
            }
            return sum;
        };
        return solve(nums, k) - solve(nums, k - 1);
    }
};